package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.UUID;


/**
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String path;
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件需要转存到指定位置  否则本次请求完成后改文件则会被删除
        log.info(file.toString());
        String filename = file.getOriginalFilename();
        filename = filename.substring(filename.indexOf("."));
        String name = UUID.randomUUID().toString().replace(".", "");
        filename = name + filename;
        System.out.println("文件名"+filename);
        //如果系统指定的文件夹不存在则自动创建
        File fileDir = new File(path);
        if(!fileDir.exists()){
            fileDir.mkdirs();
        }
        try {
            file.transferTo(new File(path+filename));
//            if(true) throw new IOException();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(filename);
    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("/download")
    public void DownLoad(String name , HttpServletResponse response){
        try {
            FileInputStream fis = new FileInputStream(new File(path + name));
            ServletOutputStream sos = response.getOutputStream();
            response.setContentType("image/jpeg");
            int len = 0;
            byte[] bytes = new byte[1024];
            while((len = fis.read(bytes)) > -1){
                sos.write(bytes,0,len);
                sos.flush();
            }
            sos.close();
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}